package com.banciyuan.bcywebview.utils.http;

import android.content.Context;
import android.os.AsyncTask;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.nio.charset.Charset;
import java.util.Map;

/**
 * Created by squall on 2015/8/13.
 */
public class OnErrorProxy implements Response.ErrorListener {

    private Response.ErrorListener error;

    private Response.Listener<String> succ;

    private String url;

    private Context context;

    private Map<String, String> map;

    public OnErrorProxy(Response.ErrorListener error, Response.Listener<String> succ, String url, Context context, Map<String, String> map) {
        this.error = error;
        this.succ = succ;
        this.url = url;
        this.context = context;
        this.map = map;
    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {

        final VolleyError errors = volleyError;

        new AsyncTask<String, String, String>() {

            @Override
            protected String doInBackground(String... strings) {

                RequestQueue queue = VolleyQueue.getRquest(context);

                String temp = url;
                String temp2 = url;

                if (null != map) {
                    for (Map.Entry<String, String> entry : map.entrySet())
                        temp += entry.getKey() + "=" + entry.getValue();
                }
                if (null != queue.getCache().get(temp)) {
                    return new String(queue.getCache().get(temp).data, Charset.defaultCharset());
                } else {
                    if (null != queue.getCache().get(temp2)) {
                        return new String(queue.getCache().get(temp2).data, Charset.defaultCharset());
                    } else {
                        return "-1";
                    }
                }
            }

            @Override
            protected void onPostExecute(String s) {
                if (s.equals("-1")) {
                    error.onErrorResponse(errors);
                } else {
                    succ.onResponse(s);
                }
            }
        }.execute();
    }
}
